package com.cy.pet.auth.service;

import com.cy.pet.auth.feign.RemoteUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登录时用户信息的获取和封装会在此对象进行实现
 * 在页面上点击登录按钮时，会调用这个对象的loadUserByUsername方法
 * 页面上输入的用户名会传给这个方法的参数
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    //UserDetails用户封装用户信息(认证和权限信息)
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户名查询用户信息(用户名，用户状态，密码，……)
        //String encodePassword = passwordEncoder.encode("123456");
        com.cy.pet.common.pojo.User user = remoteUserService.getUserByName(username);
        System.out.println(user);
        //2.查询用户权限信息(后面访问数据库)，这里先给几个假数据
        /*List<String> permissions = remoteUserService.selectPermissions(user.getId());
        System.out.println("permissions"+permissions);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{}));*/
        List<GrantedAuthority> authorities =
                AuthorityUtils.commaSeparatedStringToAuthorityList("sys:res:retrieve,sys:res:create");
        //3.对用户信息进行封装
        return new User(username,user.getPassword(),authorities);
        /*user.getPassword(),authorityList*/
    }
}
